package com.linwankaifa.linwancunyi.ui.login;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.linwankaifa.linwancunyi.R;
import com.linwankaifa.linwancunyi.bean.DoctorBean;
import com.linwankaifa.linwancunyi.bean.ManagerBean;
import com.linwankaifa.linwancunyi.bean.PatientBean;
import com.linwankaifa.linwancunyi.bean.TokenCharactor;
import com.linwankaifa.linwancunyi.ui.back.BackstageFunction;
import com.linwankaifa.linwancunyi.ui.doctor.DoctorFunction;
import com.linwankaifa.linwancunyi.ui.patient.PatientMain;
import com.linwankaifa.linwancunyi.util.Data_whole;
import com.linwankaifa.linwancunyi.util.JsonTransformation;
import com.linwankaifa.linwancunyi.util.Md5Util;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Login extends AppCompatActivity {
    // 声明两个文本编辑框
    EditText login_id;
    EditText login_password;
    Button forget;
    Button register;

    // 声明preferences
    String SHAREDPREFERENCES_NAME = "shared.xml";
    SharedPreferences preferences;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log_in);

        // 获取preference
        preferences = getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);

        // 获取编辑框
        login_id = (EditText) findViewById(R.id.login_id);
        login_password = (EditText) findViewById(R.id.login_password);

    }

    @Override
    protected void onResume() {
        super.onResume();

        Intent previous = getIntent();
        String choose = previous.getStringExtra("choose");
        if (choose.equals("backstage")) {
            forget = (Button) findViewById(R.id.forget);
            register = (Button) findViewById(R.id.register);
            forget.setText("");
            register.setText("");
        }
    }

    public void login(View view) {
        // 建立http连接
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = null;

        // 获取编辑框中的值
        String id = login_id.getText().toString();
        String password = Md5Util.StringInMd5(login_password.getText().toString());

        // 根据本地用户类型选择相应的处理
        switch (preferences.getString("usertype", "")) {
            case "patient":
                // 创建一个患者的实体类，并将其值修改为需要查询的值
                PatientBean patient = new PatientBean();
                patient.setAccountnumber(id);
                patient.setPassword(password);
                Data_whole.setPatientBean(patient);
                // 创建一个requestbody，存储由实体类patient转换成的json字符串
                requestBody = RequestBody.create(MediaType.parse("text; charset=utf-8"),
                        JsonTransformation.objectToJson(patient));
                break;
            case "doctor":
                DoctorBean doctor = new DoctorBean();
                doctor.setDoctoraccountnumber(id);
                doctor.setDoctorpassword(password);
                Data_whole.setDoctorBean(doctor);
                requestBody = RequestBody.create(MediaType.parse("text; charset=utf-8"),
                        JsonTransformation.objectToJson(doctor));
                break;
            case "back":
                ManagerBean managerBean = new ManagerBean();
                managerBean.setManageraccountnumber(id);
                managerBean.setManagerpassword(password);
                Data_whole.setManagerBean(managerBean);
                requestBody = RequestBody.create(MediaType.parse("text; charset=utf-8"),
                        JsonTransformation.objectToJson(managerBean));
                break;
            default:
                // 如果是其他角色，那么应该是出错了,直接return
                Toast.makeText(getApplicationContext(), "不正确的角色", Toast.LENGTH_SHORT).show();
                return;

        }

        // 根据不同的角色构建不同的url
        String url = getString(R.string.url)+"/";
        url += preferences.getString("usertype", "");
        url += "/login";

        // 构建请求体，并执行
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okhttp3.Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 如果失败，就显示失败信息
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast toast = Toast.makeText(getApplicationContext(), "登录失败", Toast.LENGTH_SHORT);
                        toast.show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 判断请求是否成功
                final String isSuccess = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (isSuccess) {
                            case "404":
                                Toast.makeText(getApplicationContext(), "查询错误", Toast.LENGTH_SHORT).show();
                                break;
                            default:
                                // 如果成功过则进行业务逻辑操作
                                TokenCharactor tokenCharactor = JsonTransformation.jsonToObject(isSuccess, TokenCharactor.class);

                                SharedPreferences.Editor editor = preferences.edit();
                                editor.putString("token", tokenCharactor.getToken());
                                editor.commit();
                                Log.e("login", isSuccess);

                                show();
                                switch (preferences.getString("usertype", "")) {
                                    case "patient":
                                        // 创建一个患者的实体类，并将其值修改为需要查询的值
                                        Data_whole.setPatientBean(tokenCharactor.getPatient());
                                        break;
                                    case "doctor":
                                        Data_whole.setDoctorBean(tokenCharactor.getDoctor());
                                        break;
                                    case "back":
                                        Data_whole.setManagerBean(tokenCharactor.getManager());
                                        break;
                                    default:
                                        // 如果是其他角色，那么应该是出错了,直接return
                                        Toast.makeText(getApplicationContext(), "不正确的角色", Toast.LENGTH_SHORT).show();
                                        return;

                                }

                        }
                    }
                });
            }
        });
    }

    public void show() {
        // 从前一页获取选择内容，选择切换界面
        Intent previous = getIntent();
        String choose = previous.getStringExtra("choose");
        if (choose.equals("patient")) {
            Intent intent = new Intent(Login.this, PatientMain.class);
            startActivity(intent);
        }
        if (choose.equals("doctor")) {
            Intent intent = new Intent(Login.this, DoctorFunction.class);
            startActivity(intent);
        }
        if (choose.equals("backstage")) {
            Intent intent = new Intent(Login.this, BackstageFunction.class);
            startActivity(intent);
        }
    }

    public void register(View view) {
        Intent intent = new Intent(Login.this, LoginRegister.class);
        startActivity(intent);
    }

    public void forget_password(View view) {
        Intent intent = new Intent(Login.this, LoginForgetPassword.class);
        startActivity(intent);
    }


    public void return_character(View view) {
        this.finish();
    }
}

